/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package SynchronizationLayer.Registration;

import DataModel.NotaryCertificate;
import SynchronizationLayer.Conversation;
import SynchronizationLayer.ExpectedPacket;
import SynchronizationLayer.IConversationResolver;
import SynchronizationLayer.NotarySynchronizationMessageType;
import SynchronizationLayer.NotarySynchronizationPacket;
import java.util.ArrayList;
import java.util.Collection;

public class RegistrationResolver implements IConversationResolver
{
	@Override
	public Conversation resolve( Collection<Conversation> conversations, NotarySynchronizationPacket notarySynchronizationPacket )
	{
		NotaryCertificate certificate = ( NotaryCertificate ) notarySynchronizationPacket.getNotarySynchronizationMessage().getPayload();

		for ( Conversation conversation: conversations )
		{
			if ( !certificate.getName().equals(conversation.getCertificate().getName()) )
			{
				continue;
			}

			if ( !conversation.expect(new ExpectedPacket(
							notarySynchronizationPacket.getSourceAddress(),
							new NotarySynchronizationMessageType[]
			{
				notarySynchronizationPacket.getNotarySynchronizationMessage().getNotarySynchronizationMessageType()
							})) )
			{
				continue;
			}
			return conversation;
		}
		if ( notarySynchronizationPacket.getNotarySynchronizationMessage().getNotarySynchronizationMessageType().equals(
						NotarySynchronizationMessageType.RegistrationSyn) )
		{
			Conversation conversation = new Conversation(certificate, getRegistrationBeginPackets(notarySynchronizationPacket),
																									 new RegistrationPacketHandler());
			conversations.add(conversation);
			return conversation;
		}
		else
		{
			return null;
		}
	}

	private ArrayList<ExpectedPacket> getRegistrationBeginPackets( NotarySynchronizationPacket packet )
	{
		ArrayList<ExpectedPacket> list = new ArrayList<>();

		list.add(new ExpectedPacket(packet.getSourceAddress(), new NotarySynchronizationMessageType[]
		{
			NotarySynchronizationMessageType.RegistrationSyn
		}));
		return list;
	}
}
